import pyaudio
import requests
import json

# 配置科大讯飞API参数
appid = "faa24fa0"
api_key = "3d542f1030b1538aeed37b664bd8e306"
api_secret = "NGU5ZmNhYTlmNWU0MzBhZGY1NjY3YWNk"
url = "http://api.xfyun.cn/v1/service/v1/iat"

# 初始化录音
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=1024)
print("请说话：")
frames = []
try:
    while True:
        data = stream.read(1024)
        frames.append(data)
except KeyboardInterrupt:
    print("\n录音结束")

# 保存音频数据
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open("output.wav", "wb")
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
wf.setframerate(16000)
wf.writeframes(b"".join(frames))
wf.close()

# 发送音频数据到科大讯飞API
with open("output.wav", "rb") as f:
    audio_data = f.read()
headers = {
    "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
}
data = {
    "engine_type": "sms16k",
    "aue": "raw",
    "app_id": appid,
    "format": "wav",
    "sample_rate": 16000,
    "signa": "your_signa",  # 替换为你的签名
    "token": "your_token"  # 替换为你的token
}
response = requests.post(url, headers=headers, data=data, files={"audio": audio_data})
result = json.loads(response.text)
print(result["data"])